<template>
  <div class="app-container">
    <!-- 添加或修改家政人员对话框 -->
    <el-row :gutter="20" style="margin-top: 12px">
      <el-col :xs="24" :sm="24" :md="12" :lg="7">
        <el-divider content-position="center">家政人员基本信息</el-divider>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="人员姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号码" />
          </el-form-item>
          <el-form-item label="证件照">
            <!-- <image-upload multiple
                  :limit="1" v-model="form.iconUrl"/> -->
            <el-upload class="avatar-uploader" action="" name="aboutfile" :http-request="requestUpload"
              :before-upload="beforeAvatarUpload" :on-success="handleSuccess" multiple :show-file-list="false"
              :limit="1">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="地区" prop="addressList">
            <el-cascader v-if="form.id != undefined" v-model="form.addressList" style="width: 100%" :props="props"
              :placeholder=placeholdersss></el-cascader>
            <el-cascader v-else v-model="form.addressList" style="width: 100%" :props="props"></el-cascader>
          </el-form-item>
          <el-form-item label="详细地址" prop="addressDetail">
            <el-input v-model="form.addressDetail" placeholder="请输入详细地址" />
          </el-form-item>
          <el-form-item label="出生日期" prop="birthData">
            <el-date-picker clearable style="width: 100%" v-model="form.birthData" type="date" value-format="yyyy-MM-dd"
              placeholder="请选择出生日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input v-model="form.age" placeholder="请输入年龄" />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-select v-model="form.sex" placeholder="请选择" style="width: 100%">
              <el-option v-for="item in xingbietypes" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工作年限" prop="yearNum">
            <el-input v-model="form.yearNum" placeholder="请输入工作年限" />
          </el-form-item>
          <el-form-item label="服务内容" prop="contentsList">
            <el-checkbox-group v-model="form.contentsList">
              <el-checkbox label="1">做饭</el-checkbox>
              <el-checkbox label="2">做家务</el-checkbox>
              <el-checkbox label="3">照顾小孩</el-checkbox>
              <el-checkbox label="4">照顾老人</el-checkbox>
              <!-- <el-checkbox label="选中且禁用"></el-checkbox> -->
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="服务类型" prop="serveType">
            <el-select v-model="form.serveType" placeholder="请选择" style="width: 140px">
              <el-option v-for="item in fuwutypes" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <el-input-number v-model="form.serveMoney" @change="handleChange" :min="1" :max="1000000" label="请输入价格"
              style="margin-left: 20px"></el-input-number>
            <span style="font-size: 16px; margin-left: 10px">元</span>
          </el-form-item>
          <el-form-item label="个人展示" prop="serveMoney">
            <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="form.explainStr">
            </el-input>
          </el-form-item>
          <el-form-item label="">
            <el-upload class="avatar-uploader" action="" :file-list="fileList" name="aboutfile" :http-request="Uploadzhanshi"
              :before-upload="beforeAvatarUpload" :on-remove="removeCallback" :on-success="handlesss" multiple>
<!--              <img  v-if="imageUrlsss" :src="imageUrlsss" class="avatar">-->
<!--                <img  v-for="item in fileList" v-if="fileList.length>0" :src="item.url" class="avatar">-->
<!--              <i v-if="fileList.length==0" class="el-icon-plus avatar-uploader-icon"></i>-->
              <i  class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <div style="min-width: 400px;display: flex;flex-wrap: wrap;margin-left:80px"><img  v-for="item in fileList" v-if="fileList.length>0" :src="item.url" class="avatar"></div>
        </el-form>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12" :lg="11">
        <el-divider content-position="center">家政人员工作经历信息</el-divider>
        <el-form ref="form2" :model="form2" :rules="rules" label-width="80px">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddJzLaborerHistory">添加
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteJzLaborerHistory">删除
              </el-button>
            </el-col>
          </el-row>
          <el-table :data="historyList" :row-class-name="rowJzLaborerHistoryIndex"
            @selection-change="handleJzLaborerHistorySelectionChange" ref="jzLaborerHistory">
<!--            <el-table-column type="selection" width="50" align="center" />-->
            <el-table-column label="工种" prop="laborerTypeStr" width="100">
              <template slot-scope="scope">
                <el-input v-model="scope.row.laborerTypeStr" placeholder="请输入工种" />
              </template>
            </el-table-column>
            <el-table-column label="开始时间" prop="timeStart" width="170">
              <template slot-scope="scope">
                <el-date-picker style="width: 100%" clearable v-model="scope.row.timeStart" type="date"
                  value-format="yyyy-MM-dd" placeholder="请选择开始时间" />
              </template>
            </el-table-column>
            <el-table-column label="结束时间" prop="timeEnd" width="170">
              <template slot-scope="scope">
                <el-date-picker style="width: 100%" clearable v-model="scope.row.timeEnd" type="date"
                  value-format="yyyy-MM-dd" placeholder="请选择结束时间" />
              </template>
            </el-table-column>
            <el-table-column label="工作内容" prop="historyDetail" width="250">
              <template slot-scope="scope">
                <el-input type="textarea" :rows="8" v-model="scope.row.historyDetail" placeholder="请输入工作内容" />
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12" :lg="6">
        <el-divider content-position="center">家政人员预约时间设置</el-divider>
        <div class="timesss">
          <el-checkbox-group v-model="form.timesList" style="border: none">
            <el-checkbox-button v-for="city in cities" :label="city" :key="city">{{city}}</el-checkbox-button>
          </el-checkbox-group>
        </div>
        <div style="margin-top: 100px; margin-left: 200px">
          <el-button v-if="this.form.id == undefined" type="primary" @click="submitForm('form')">发 布</el-button>
          <el-button v-else type="primary" @click="submitForm('form')">修 改</el-button>
          <el-button @click="cancel">返 回</el-button>
        </div>
      </el-col>
      <!-- </el-dialog> -->
    </el-row>
  </div>
</template>

<script>
  import {
    listLaborer,
    getLaborer,
    delLaborer,
    addLaborer,
    updateLaborer,
    getregion,
    uploadimg,
    uploadqiniu
  } from "@/api/system/laborer";
  let addressStrList = []
  // let id = 0;
  export default {
    name: "Laborer",
    data() {
      return {
        props: {
          lazy: true,
          lazyLoad(node, resolve) {
            if (node.data) {
				if (node.data.parentId === '0') {
				  addressStrList = []
				}
              addressStrList.push(node.data)
            }
            // console.log(addressStrList)
            const {
              level
            } = node;
            let data = []
            // setTimeout(() => {
            let id = 0
            // console.log(level)
            if (level != 0) {
              id = node.value
            }
            // console.log(node.data.label)
            getregion(id).then(res => {
              res.rows.map(item => {
                console.log(item)
                let obj = {
                  value: item.id,
                  label: item.name,
					parentId: item.parentId
                }
                // console.log(obj)
                data.push(obj)
              })
              resolve(data);
            });
            // }, 1000);
            // 通过调用resolve将子节点数据返回，通知组件数据加载完成
          }
        },
        xingbietypes: [{
          value: 0,
          label: '男'
        }, {
          value: 1,
          label: '女'
        }],
        fuwutypes: [{
          value: 1,
          label: '住家'
        }, {
          value: 2,
          label: '白班'
        }, {
          value: 3,
          label: '钟点工'
        }],
        checkboxGroup1: ['上海'],
        cities: ['06:00-07:00', '07:00-08:00', '08:00-09:00', '09:00-10:00', '10:00-11:00', '11:00-12:00', '12:00-13:00',
          '13:00-14:00', '14:00-15:00', '15:00-16:00', '16:00-17:00',
          '17:00-18:00', '18:00-19:00',
          '19:00-20:00', '20:00-21:00', '21:00-22:00', '22:00-23:00', '23:00-24:00'
        ],
        cityarr: [],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 子表选中数据
        checkedJzLaborerHistory: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 家政人员表格数据
        laborerList: [],
        // 家政人员工作经历表格数据
        historyList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: null,
          phone: null,
          serveType: null,
        },
        querysele: '',
        house: '',
        // 表单参数
        form: {
          timesList: [],
          contentsList: [],
          serveMoney: ''
        },
        // 表单校验
        rules: {
          name: [{
            required: true,
            message: "姓名不能为空",
            pattern: /^\S*$/,
            trigger: "blur"
          }],
          phone: [{
            required: true,
            message: "手机号不能为空",
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            trigger: "blur"
          }],
          addressList: [{
            required: true,
            message: "地区不能为空",
            trigger: "change"
          }],
          addressDetail: [{
            required: true,
            message: "详细地址不能为空",
            pattern: /^\S*$/,
            trigger: "blur"
          }],
          birthData: [{
            required: true,
            message: "出生日期不能为空",
            trigger: "blur"
          }],
          age: [{
            required: true,
            message: "年龄不能为空",
            pattern: /^[0-9]*$/,
            trigger: "blur"
          }],
          sex: [{
            required: true,
            message: "性别不能为空",
            trigger: "change"
          }],
          yearNum: [{
            required: true,
            message: "工作年限不能为空",
            pattern: /^[0-9]*$/,
            trigger: "blur"
          }],
          contentsList: [{
            required: true,
            message: "服务内容不能为空",
            trigger: "change"
          }],
          serveType: [{
            required: true,
            message: "服务类型不能为空",
            trigger: "change"
          }],
        },
        form2: {},
        placeholdersss: '',
        imageUrl: '',
        imageUrlsss: '',
        urlarr: [],
        imgUrlList: [],
        fileList:[],
        testList:[]
      };
    },
    created() {
      // this.getList();
      // console.log(this.form.id)
      this.form.id = this.$route.query.id
      // console.log(this.form.id)
      if (this.form.id != undefined) {
        this.getdet()
      }
    },
    methods: {
      getdet() {
        const id = this.form.id
        getLaborer(id).then(response => {
          // console.log(response)
          // this.form.sex = Number(response.data.sex)
          this.form = response.data;
          this.placeholdersss = response.data.addressOneStr + response.data.addressTwoStr + response.data
            .addressThreeStr + response.data.addressFourStr
          this.historyList = response.data.historyList;
          this.imageUrl = response.data.iconUrl
          // console.log("rrrrrrr",response.data.imgUrlList)
          // this.fileList=response.data.imgUrlList.split(',')
          // console.log("123",this.fileList)
          // this.testList=response.data.imgUrlList.split(',')
          if(response.data.imgUrlList){
            response.data.imgUrlList.split(',').forEach(item => {
              console.log("imgUrlList",item)
              this.imageUrlsss = item
              this.fileList.push({name:item,url:item})
            })
          }

        });
      },
      handleChange(value) {
        console.log(value);
      },
      handleChange(value) {
        console.log(value);
      },
      //删除
      removeCallback(file, fileList){
        console.log("删除",file, fileList)
        let uid=file.uid
        for(let i=0;i<this.fileList.length;i++){
          if(this.fileList[i].uid==uid){
            this.fileList.splice(i,1)
          }
        }
      },
      // 上传图片
      requestUpload(params) {
        // console.log(params)
        let formData = new FormData();
        formData.append("file", params.file);
        uploadimg(formData).then(res => {
          params.onSuccess(res);
          // console.log(res)
          let token = res.data
          if (res.code == 200) {
            let formDatasss = new FormData();
            // console.log(token)
            formDatasss.append("key", "user/" + this.globalGetUuid());
            formDatasss.append("token", token);
            formDatasss.append("file", params.file);
            uploadqiniu(formDatasss).then(res => {
              // console.log(res)
              let url = "http://q.shaxiansong.com/" + res.key;
              // console.log(url)
              this.form.iconUrl = url
            });
          }
        });
      },
      Uploadzhanshi(params) {
        console.log("eererrrr",params)
        let formData = new FormData();
        formData.append("file", params.file);
        console.log("params.file",params.file)
        // formData.append("file", this.fileList);
        uploadimg(formData).then(res => {
          params.onSuccess(res);
          // console.log(res)
          let token = res.data
          if (res.code == 200) {
            let formDatasss = new FormData();
            // console.log(token)
            formDatasss.append("key", "user/" + this.globalGetUuid());
            formDatasss.append("token", token);
            formDatasss.append("file", params.file);
            uploadqiniu(formDatasss).then(res => {
              // console.log(res)
              // let urlarr = []
              this.urlarr.push(res.key)
              // console.log(this.urlarr)
              let imgUrlList = []
              this.urlarr.forEach(item => {
                let itemsss = {
                  url: "http://q.shaxiansong.com/" + item
                }
                imgUrlList.push(itemsss.url)

                // console.log(this.imgUrlList)

              })
              let set = [...new Set(imgUrlList)]
              // console.log(set)
              this.form.imgUrlList = set.toString()
              console.log("this.form.imgUrlList",this.form.imgUrlList)
              let arrTest=this.form.imgUrlList.split(',')
              let last = arrTest[arrTest.length-1]
              this.fileList.push({name:last,url:last})
              console.log("this.form.fileList",this.fileList)
            });
          }
        });
      },
      globalGetUuid() {
        let d = new Date().getTime();
        const uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
          /[xy]/g,
          function(c) {
            const r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c == "x" ? r : (r & 0x7) | 0x8).toString(16);
          }
        );
        return uuid;
      },
      beforeAvatarUpload() {

      },
      handleSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      //改
      handlesss(res, file) {
        console.log("filedddddd",file)
        // this.imageUrlsss = URL.createObjectURL(file.raw);
        // this.fileList.push({name:file.name,url:URL.createObjectURL(file.raw)})
      },
      /** 查询家政人员列表 */
      getList() {
        this.loading = true;
        listLaborer(this.queryParams).then(response => {
          this.laborerList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        //   this.open = false;
        this.reset();
        this.$router.push({
          path: '/housekeep'
        })
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          name: null,
          phone: null,
          addressOneId: null,
          addressOneStr: null,
          addressTwoId: null,
          addressTwoStr: null,
          addressThreeId: [],
          addressThreeStr: null,
          addressDetail: null,
          birthData: null,
          age: null,
          sex: null,
          yearNum: null,
          sort: null,
          iconUrl: null,
          serveType: null,
          serveTypeName: null,
          serveMoney: null,
          serveMoneyStr: null,
          tel: null,
          status: 0,
          createId: null,
          createTime: null,
          updateId: null,
          updateTime: null,
          delFlag: null
        };
        this.historyList = [];
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加家政人员";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getLaborer(id).then(response => {
          this.form = response.data;
          this.historyList = response.data.historyList;
          this.open = true;
          this.title = "修改家政人员";
        });
      },
      /** 提交按钮 */
      submitForm(form) {
        let testList=this.fileList.map(item =>item.url)
        this.form.imgUrlList=[...new Set(testList)].toString()
        this.$refs[form].validate(valid => {
          if (valid) {
            // console.log(this.form)
            if (this.form.id != undefined) {
              // console.log(456)
              if (this.form.iconUrl == '' || this.form.iconUrl == undefined) {
                  this.$message.error('请上传证件照！');
                  return false
                }
                if (this.historyList.length == 0) {
                  this.$message.error('请填写工作经历信息！');
                  return false
                }
                if (this.form.timesList.length == 0) {
                  this.$message.error('请设置预约时间！');
                  return false
                }
                this.form.historyList = this.historyList;
                let sss = []
                addressStrList.forEach(item => {
                  // console.log(item.label)
                  sss.push(item.label)
                })
                this.form.addressStrList = sss
              updateLaborer(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.form.addressStrList = []
                this.$router.push({
                  path: '/housekeep'
                })
              });
            } else {
              if (this.form.iconUrl == '' || this.form.iconUrl == undefined) {
                this.$message.error('请上传证件照！');
                return false
              }
              if (this.historyList.length == 0) {
                this.$message.error('请填写工作经历信息！');
                return false
              }
              if (this.form.timesList.length == 0) {
                this.$message.error('请设置预约时间！');
                return false
              }
              // console.log(123)
              // let cons = this.form.contentsList
              // this.form.contentsList = JSON.stringify(this.form.contentsList)
              let sss = []
              addressStrList.forEach(item => {
                // console.log(item.label)
                sss.push(item.label)
              })
              this.form.addressStrList = sss
              this.form.historyList = this.historyList;
              addLaborer(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.form.addressStrList = []
                this.$router.push({
                  path: '/housekeep'
                })
              });
            }
          } else {
            this.$message.error('必填项不能为空！');
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除家政人员编号为"' + ids + '"的数据项？').then(function() {
          return delLaborer(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 家政人员工作经历序号 */
      rowJzLaborerHistoryIndex({
        row,
        rowIndex
      }) {
        row.index = rowIndex + 1;
      },
      /** 家政人员工作经历添加按钮操作 */
      handleAddJzLaborerHistory() {
        let obj = {};
        obj.laborerTypeStr = "";
        obj.timeStart = "";
        obj.timeEnd = "";
        obj.historyDetail = "";
        obj.createId = "";
        obj.updateId = "";
        this.historyList.push(obj);
      },
      /** 家政人员工作经历删除按钮操作 */
      handleDeleteJzLaborerHistory() {
        if (this.checkedJzLaborerHistory.length == 0) {
          this.$modal.msgError("请先选择要删除的家政人员工作经历数据");
        } else {
          const historyList = this.historyList;
          const checkedJzLaborerHistory = this.checkedJzLaborerHistory;
          this.historyList = historyList.filter(function(item) {
            return checkedJzLaborerHistory.indexOf(item.index) == -1
          });
        }
      },
      /** 复选框选中数据 */
      handleJzLaborerHistorySelectionChange(selection) {
        this.checkedJzLaborerHistory = selection.map(item => item.index)
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/laborer/export', {
          ...this.queryParams
        }, `laborer_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
<style>
  .timesss {
    width: 100%;
    margin: 0 auto;
  }

  .timesss .el-checkbox-group {
    width: 90%;
    margin: 0 auto;
    /* text-align: center; */
  }

  .el-checkbox-button__inner {
    border: 1px solid #ccc;
    margin-right: 10px;
    margin-top: 10px;
  }

  .el-input-number {
    width: 130px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
